<!-- 个人资料设置 -->
<template>
  <div class="userInfom">
    <a-modal
      class="inform-modal"
      title="个人设置"
      width="800px"
      :visible="informVisible"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="form"
        :rules="rules"
        :colon="false"
        v-bind="formLayout"
        class="inform-form"
        style="height:auto;"
      >
        <!-- 个人信息 -->
        <a-row :gutter="24">
          <a-col :span="4">
            <a-form-model-item prop="userAvatar">
              <a-upload
                name="file"
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :customRequest="uploadImage"
                :beforeUpload="beforeUpload"
                accept="image/jpeg, image/jpg, image/png"
              >
                <!--  @preview="handlePreview"-->
                <div class="avatar">
                  <img
                    :src="informData.imageUrl ? informData.imageUrl : require('../../../assets/images/avatar.png')"
                  />
                  <!-- <a-icon class="uploading-icon" :class="avatarLoading&&'show'" type="loading" /> -->
                </div>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="20">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="用户名" prop="userName">
                  <span>{{informData.userName}}</span>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="手机号" prop="userPhone" v-show="isPhoneEdit===false">
                  <span>{{informData.userPhone}}</span>
                  <a style="marginLeft: 24px" @click="mobileEdit()">修改</a>
                </a-form-model-item>
                <a-form-model-item label="手机号" prop="userPhone" v-show="isPhoneEdit===true">
                  <a-input style="width: 50%;" v-model="informData.userPhone" />
                  <i @click="submitData('userPhone')" class="iconfont iconsuccess"></i>
                  <i @click="emptyData('userPhone')" class="iconfont iconerror" style="color:red"></i>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="邮箱" prop="userEmail" v-show="isEmailEdit===false">
                  <span>{{informData.userEmail}}</span>
                  <a style="marginLeft: 24px;" @click="emailEdit()">修改</a>
                </a-form-model-item>
                <a-form-model-item label="邮箱" prop="userEmail" v-show="isEmailEdit===true">
                  <a-input style="width: 80%" v-model="informData.userEmail" />
                  <i @click="submitData('userEmail')" class="iconfont iconsuccess"></i>
                  <i @click="emptyData('userEmail')" class="iconfont iconerror" style="color:red"></i>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="单位名称" prop="userOrgName">
                  <a-input
                    class="input-unitName"
                    v-model="informData.userOrgName"
                    autocomplete="off"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-divider />
        </a-row>
        <a-row :gutter="24">
          <!-- 我的标签 -->
          <div class="tags-header">
            <a-icon type="pushpin" theme="filled" />
            <span>我的标签</span>
          </div>
          <div class="tags-content">
            <div style="marginBottom: 10px">
              <template v-for="tag in informData.defaultTags">
                <a-tag
                  :key="tag"
                  :style="{fontSize: tag.length >= 6 ? '10px' : '16px'}"
                  class="tag-default"
                >{{ tag}}</a-tag>
              </template>
            </div>
            <div>
              <!-- <template v-for="tag in informData.attentionTags">
                <a-tag
                  :key="tag"
                  :style="{fontSize: tag.length >= 6 ? '10px' : '16px'}"
                  class="tag-attention"
                >{{ tag}}</a-tag>
              </template> -->

              <template v-for="(tag, index) in informData.addTags">
                <a-badge :key="tag" class="tag-badge">
                  <a-icon
                    slot="count"
                    :key="index"
                    type="close-circle"
                    theme="filled"
                    class="tag-icon"
                    @click="handleClose(tag)"
                  ></a-icon>
                  <a-tag
                    :key="tag"
                    class="tag-add"
                    :style="{fontSize: tag.length >= 6 ? '10px' : '16px'}"
                  >{{ tag }}</a-tag>
                </a-badge>
              </template>

              <a-input
                v-if="inputVisible"
                ref="input"
                type="text"
                class="tag-input"
                :maxLength="6"
                :value="inputValue"
                @change="handleInputChange"
                @blur="handleInputConfirm"
                @keyup.enter="handleInputConfirm"
              />
              <a-tag class="tag-span-add" @click="showInput">添加标签</a-tag>
            </div>
          </div>
        </a-row>
      </a-form-model>
      <template slot="footer">
        <div class="inform-footer">
          <a-button class="submit-btn" type="primary" @click="submitForm('form')">确定</a-button>
          <a-button class="close-btn" @click="handleCancel()">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
export default {
  props: {
    saveFunc: {
      type: Function,
      default: () => {},
    },
    informData: {
      type: Object,
      default: null,
    },
    informVisible: {
      type: Boolean,
      default: false,
    },
    closeFunc: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      formLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 10 },
      },
      isPhoneEdit: false,
      isEmailEdit: false,
      avatarLoading: false,
      rules: {
        name: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
          {
            min: 3,
            max: 5,
            message: "Length should be 3 to 5",
            trigger: "blur",
          },
        ],
        mobile: [
          // {
          //   max: 11,
          //   message: "长度不合法, 手机号限11位",
          //   trigger: ["blur", "change"],
          // },
          // {
          //   validator: (rule, value, callback) => {
          //     const number = /^[0-9]+$/;
          //     if (value && !number.test(value)) {
          //       callback(new Error("只允许输入数字"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: ["blur", "change"],
          // },
          // {
          //   pattern: /^1(3|4|5|6|7|8)\d{9}$/,
          //   message: "请输入正确的手机号",
          // },
          { required: true, trigger: "blur" },
        ],
      },
      //添加标签input显示
      inputVisible: false,
      inputValue: "",
      previewVisible: false,
      previewImage: "",
      fileList: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //关闭标签事件
    handleClose(removedTag) {
      const tags = this.informData.addTags.filter((tag) => tag !== removedTag);
      console.log(tags);
      this.informData.addTags = tags;
    },
    //添加标签事件
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },
    //添加标签inputchange事件
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },
    //确认添加标签事件
    handleInputConfirm() {
      const inputValue = this.inputValue;
      console.log("input:", inputValue);
      let tags = this.informData.addTags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      console.log("tags:", tags);
      this.informData.addTags = tags;
      Object.assign(this, {
        inputVisible: false,
        inputValue: "",
      });
      console.log("addTags", this.informData.addTags);
    },
    //修改手机号
    mobileEdit() {
      this.isPhoneEdit = true;
    },
    //修改邮箱
    emailEdit() {
      this.isEmailEdit = true;
    },
    //
    submitData(type) {
      let that = this;
      if (type === "userPhone") {
        this.isPhoneEdit = false;
        this.$message.warning("哈哈哈");
      } else if (type === "userEmail") {
        this.isEmailEdit = false;
      }
    },
    //表单提交事件
    submitForm() {
      this.$refs.form.validate((valid) => {
        console.log("valid:", valid);
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      this.isPhoneEdit = false;
      this.isEmailEdit = false;
      this.$emit("saveFunc");
    },
    //重置表单
    resetForm() {
      this.$refs.form.resetFields();
    },
    //取消修改数据
    emptyData(type) {
      console.log("type:", type);
      this.$refs.form.resetFields();
      if (type === "userPhone") {
        this.isPhoneEdit = false;
      } else if (type === "userEmail") {
        this.isEmailEdit = false;
      }
    },
    //弹窗关闭
    handleCancel(e) {
      console.log("点击了取消按钮");
      this.$emit("closeFunc");
    },
    /**用户更改头像 */
    // 上传头像前校验
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("只能上传jpg/png格式的头像!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片不得大于2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    // 上传头像
    uploadImage(file) {
      console.log("头像file:", file);
      this.avatarLoading = true;
      const formData = new FormData();
      formData.append("file", file.file);
      // api.upload(formData).then(
      //   (res) => {
      //     if (res) {
      // this.form.imageUrl = res.data.data.link;
      this.informData.imageUrl = require("../../../assets/images/avatar-img.png");
      this.saveAvatar(); // 保存新头像
      this.avatarLoading = false;
      //     }
      //   },
      //   (err) => {
      //     this.avatarLoading = false;
      //   }
      // );
    },
    saveAvatar() {},
    /**用户头像预览 */
    // async handlePreview(file) {
    //   if (!file.url && !file.preview) {
    //     file.preview = await getBase64(file.originFileObj);
    //   }
    //   this.previewImage = file.url || file.preview;
    //   this.previewVisible = true;
    // },
    // handlePreviewCancel() {
    //   this.previewVisible = false;
    // },
    // getBase64(file) {
    //   return new Promise((resolve, reject) => {
    //     const reader = new FileReader();
    //     reader.readAsDataURL(file);
    //     reader.onload = () => resolve(reader.result);
    //     reader.onerror = (error) => reject(error);
    //   });
    // },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
};
</script>
<style lang='stylus' scoped>
.inform-form
  span
    font-size 16px
    margin-left 8px
    color #333333
  .input-unitName
    width 100%
    font-size 16px
    font-weight 500
  .iconfont
    margin 0px 0px 0px 8px
    cursor pointer
    color #87d068
  .tags-header
    span
      margin-left 8px
      font-size 14px
      font-weight 600
  .tags-content
    .tag-default
      background #F5F5F5
      border 0px
      color #B8B8B8
    .tag-attention
      background #089DFF
      border 0px
      color #fff
      cursor pointer
    .tag-add
      background #089DFF
      border 0px
      color #fff
      cursor pointer
    .tag-input
      width 100px
      padding 8px
      margin 0px 8px
      border-radius 30px
      height 38px
      background #F5F5F5
      border 0px
      color #000
      text-align center
    .tag-span-add
      color #1678FD
      font-size 14px
      border 0px
      background #fff
      cursor pointer
    .tag-badge
      position relative
      margin-left 0
    .tag-badge >.tag-icon
      display: none
    .tag-badge:hover >.tag-icon
      display block
      position absolute
      right 8%
      top 10%
      font-size 20px
      color #FF8B19
.inform-footer
  .submit-btn
    width 76px
    height 34px
    margin 0px 20px
    border 1px solid #1678FD
    background #1678FD
  .close-btn
    width 76px
    height 34px
    margin 0px 20px
    border 1px solid #1678FD
    color #1678FD
</style>